package action.back;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import models.Orgn;
import models.Role;
import models.User;
import models.UserRole;
import models.Zone;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.hibernate.FetchMode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import utils.JsonUtils;
import utils.StringHelper;
import config.Constant;

public class UserAction extends DefaultAction {
	
	private User user;
	
	public String index() {
		return "index";
	}
	
	
	@SuppressWarnings("unchecked")
	public void getTrees() {
		boolean if_orgn   = StringHelper.parseBoolean(request.getParameter("if_orgn"));
		Integer zone_id   =  Integer.parseInt(request.getParameter("zone_id"));
		Integer parent_id = Integer.parseInt(request.getParameter("parent_id"));

		List<Orgn> orgns = new ArrayList<Orgn>();
		List<Zone> zones = new ArrayList<Zone>();
		if(!if_orgn){
			if (zone_id == null || zone_id.intValue() == 0) {
				zones = getCommonService().findAll(Zone.class, "position asc", "parent is null",null);
			} else {
				zones = getCommonService().findAll(Zone.class, "position asc", "parent.id = ?",new Object[]{zone_id});
			}
		}
		
		if (parent_id == null || parent_id.intValue() == 0) {
			orgns = getCommonService().findAll(Orgn.class, "position asc", "zone.id = ? and parent is null",new Object[]{zone_id});
		} else {
			orgns = getCommonService().findAll(Orgn.class, "position asc", "zone.id = ? and parent.id=?",new Object[]{zone_id,parent_id},"zone");
		}
		
		List<Map> trees = new ArrayList<Map>();
		
		for (Zone zone : zones) {
			Map<String, Object> tree = new HashMap<String, Object>();
			tree.put("id", "Z_" + zone.getId());
			tree.put("text", zone.getName());
			tree.put("iconCls", "admin-tool-zone");
			tree.put("leaf", zone.getSubZoneCount() + zone.getSubOrgnCount() == 0);
			tree.put("if_orgn", Constant.FALSE);
			tree.put("zone_id", zone.getId());
			tree.put("parent_id", "0");
			trees.add(tree);
		}
		
		for (Orgn orgn : orgns) {
			Map<String, Object> tree = new HashMap<String, Object>();
			tree.put("id", orgn.getId());
			tree.put("text", orgn.getName());
			tree.put("iconCls", "admin-tool-orgn");
			tree.put("leaf", orgn.getSubOrgnCount() == 0);
			tree.put("if_orgn", Constant.TRUE);
			tree.put("zone_id", orgn.getZone().getId());
			tree.put("parent_id", orgn.getId());
			trees.add(tree);
		}
		
		JSONArray jsonObject = JSONArray.fromObject(trees);
		String jsonString = jsonObject.toString();
		renderJson(jsonString);
		
	}
	
	@SuppressWarnings("unchecked")
	public void getChildren() {
		Integer parent_id = Integer.parseInt(request.getParameter("parent_id"));
		Integer zone_id = Integer.parseInt(request.getParameter("zone_id"));
		
		DetachedCriteria dc = DetachedCriteria.forClass(User.class);
		
		if(zone_id>0){
			String zoneCode = getCommonService().findString("select code from Zone where id=?", zone_id);
			dc.createAlias("zone", "zoneObj");
			dc = zoneRestrion(dc,"zoneObj.code",zoneCode);
		}

		dc.setFetchMode("zone", FetchMode.JOIN);
		dc.setFetchMode("orgn", FetchMode.JOIN);
		if(parent_id>0)
			dc.add(Restrictions.eq("orgn.id", parent_id));
	    page = getCommonService().findPage(dc, start, limit);
	    
	    
	    Map<String, Object> jsonMap = new HashMap<String, Object>();
	    jsonMap.put("items",JsonUtils.toMapList(page.getItems(), "user"));
	    jsonMap.put("total", page.getTotal());
	    JsonConfig config = new JsonConfig();
	    //config.setJsonPropertyFilter(new IgnoreFieldProcessorImpl(true)); // 忽略掉集合对象
	    
	    JSONObject jsonObject = JSONObject.fromObject(jsonMap,config);
	    
		String jsonString = jsonObject.toString();
		renderJson(jsonString);
	}
	


	public void save() {
		boolean isExist = false;
		if(user.getId()!=null && user.getId()!=0){
			isExist = getCommonService().isExist(User.class,"loginname",user.getLoginname(),"id!=?",new Object[]{user.getId()});
		}
		else{
			isExist = getCommonService().isExist(User.class,"loginname",user.getLoginname(),null,null);
		}
		
		if(isExist){
			renderJson("{msg:'"+"用户名："+user.getLoginname()+"已经存在!'}");
		}
		else{
			getCommonService().saveOrUpdate(user);
			renderJson("{success:true}");
		}
		
	}
	
	public void delete() {
		for(Integer id : ids){
			getCommonService().executeUpdate("delete UserRole where user.id = ?", id);
			getCommonService().executeUpdate("delete User where id = ?", id);
		}
		
		renderJson("{success:true}");
	}
	
	@SuppressWarnings("unchecked")
	public void getRoleTrees() {

		Integer user_id = Integer.parseInt(request.getParameter("user_id"));
		
		List<Integer> roleids = getCommonService().findAll("select role.id from UserRole where user.id=?", user_id);
		
		List<Role> roles =  getCommonService().findAll("from Role");
		
		List<Map> trees = new ArrayList<Map>();
		for (Role role : roles) {
			Map<String, Object> tree = new HashMap<String, Object>();
			tree.put("id", role.getId());
			tree.put("text", role.getName());
			tree.put("leaf", true);
			tree.put("checked", roleids.contains(role.getId()));
			tree.put("iconCls", "admin-tool-role");
			trees.add(tree);
		}
		
		JSONArray jsonObject = JSONArray.fromObject(trees);
		String jsonString = jsonObject.toString();
		renderJson(jsonString);
	}
	
	public void saveUserRole() {
		
		getCommonService().executeUpdate("delete UserRole where user=?", user);
		
		for(Integer role_id : ids){
			UserRole ur = new UserRole();
			ur.setUser(user);
			
			Role role = new Role();
			role.setId(role_id);
			ur.setRole(role);
			getCommonService().save(ur);
		}
		
		renderJson("{success:true}");
	}
	
	public void savePwd() {
		String passwrod = request.getParameter("passwd");
		Integer id = getLoginInfo().getUser().getId();
		getCommonService().executeUpdate("update User set password=? where id=?", passwrod,id);
		renderJson("{success:true}");
	}
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
}
